<?php
/**
 * Controller of all actions related to view/set medicines and materials used by a patient

 * @package core.controllers
 * @author ppdong
 * @version $Id$
 * @copyright 2009 LHV Company
 *
 */
$loader->requireOnce('controllers/C_Medicine.class.php');
$loader->requireOnce('controllers/C_MedicalMaterial.class.php');
class C_TicketMedicine extends Controller {
    public function __construct($template_mod = "general"){
    	parent::__construct();
        $this->_db = $GLOBALS['frame']['adodb']['db'];
        if (Celini::getCurrentController() == 'TicketMedicine') {
            $menu =& Menu::getInstance();
            $menu->currentSection = 'patient';
        }
        $this->template_mod = $template_mod;
        $this->view->path = 'ticket_medicine';
    }

    public function actionViewTicketMedicineDetail($ticketId='', $dateFrom='',
            $dateTo='', $filter = false){
    	 if(isset($_GET['ticketId'])){
    	 	$ticketId    =   $_GET['ticketId'];
    	 }
    	 if (isset($_GET['filter']) && $_GET['filter']==='byDate'){
            $filter  =   true;
    	 }
    	 else {
    	 	$filter  =   false;
    	 }
    	 if(isset($_GET['dateFrom'])){
    	    $dateFrom =   L10nHelper::getISODate($_GET['dateFrom']);
    	 }
         if(isset($_GET['dateTo'])){
            $dateTo =   L10nHelper::getISODate($_GET['dateTo']);
         }
         $res   =   self::getTicketMedicineData($ticketId, $dateFrom, $dateTo, $filter);
         $this->assign('medicineList', $res['medicineList']);
         $this->assign('medIndex', 1);
         $this->assign('materialList', $res['materialList']);
         $this->assign('insIndex', 1);
         $this->assign('ticketId', $ticketId);

         return $this->view->render('detail_view_medicine.html');
    }

    public function actionViewTicketMedicine($ticketId = ''){
    	if(isset($_GET['ticketId'])){
    		$ticketId =   $_GET['ticketId'];
    	}
    	$objTicket     =   ORDataObject::factory('PatientTransferHistory')->getObjectByTicketId($ticketId);
        $start      =   explode(" ", $objTicket->get('start_time'));
        $end        =   explode(" ", $objTicket->get('end_time'));
        if ($end[0] == "0000-00-00" || empty($end[0])) {
            $endDate    =   date('Y-m-d');
        }
        else {
            $endDate   =   $end[0];
        }
        $issueDates    =   Utils::getDateList($start[0], $endDate);
        $orders =   L10nHelper::getYMDorder();

    	$this->assign('datePart_0', $orders[0]);
        $this->assign('datePart_1', $orders[1]);
        $this->assign('datePart_2', $orders[2]);
        $this->assign('issueDates', $issueDates);

    	return $this->view->render('view_ticket_medicine.html');
    }

    public function actionInputTicketMedicine($ticketId = ''){
    	if(isset($_GET['ticketId'])){
    		$ticketId =   $_GET['ticketId'];
    	}
    	$objTicket     =   ORDataObject::factory('PatientTransferHistory')->getObjectByTicketId($ticketId);
    	$start         =   explode(" ", $objTicket->get('start_time'));
    	$end           =   explode(" ", $objTicket->get('end_time'));
        if ($end[0] == "0000-00-00" || empty($end[0])) {
            $endDate    =   date('Y-m-d');
        }
        else {
        	$endDate   =   $end[0];
        }

    	$issueDates    =   Utils::getDateList($start[0], $endDate);
    	$objEmployee   =   ORDataObject::factory('Employee');
    	$departmentId  =   $this->_me->get_department_id(); //TODO: Consider get departmentId by other source
    	$doctorList    =   $objEmployee->getEmployeeOfDepartment($departmentId,
            EmployeeType::DOCTOR_ID, true);
    	$employeeList  =   $objEmployee->getEmployeeOfDepartment($departmentId,
            array(EmployeeType::DOCTOR_ID, EmployeeType::NURSING_ID), true);
    	$this->assign("issueDates", $issueDates);
    	$this->assign("doctorList", $doctorList);
    	$this->assign("employeeList", $employeeList);
    	 $this->assign('ticketId', $ticketId);

    	return $this->view->render('input_ticket_medicine.html');
    }

    public function actionInputMedicineDetail($ticketId='', $issueDate=''){
    	if(isset($_GET['ticketId'])){
    		$ticketId =   $_GET['ticketId'];
    	}
    	if(isset($_GET['issueDate'])){
            $issueDate  =   L10nHelper::getISODate($_GET['issueDate']);
    	}
        $res    =   self::getTicketMedicineData($ticketId, $issueDate, $issueDate, true);
        $medicine   =   array(
                'medicine_id'       => '',
                'medicine_name'     => '',
                'quantity_num'      => '',
                'quantity_title'    => '',
                'unit_price'        => '',
                'original_price'    => '',
                'insurance_price'   => '',
                'patient_price'     => '',
                'issue_date'        => '',
                'issue_person'      => '',
                'issue_person_name' => '',
                'doctor'            => '',
                'doctor_id'         => ''
            );
        if (empty($res['medicineList'])) {
        	for ($i=0; $i < 1; $i++){
                $res['medicineList'][$i]    =   $medicine;
            }
        }
        else {
        	array_push($res['medicineList'], $medicine);
        }

        $material   =   array(
                'material_id'       => '',
                'material_name'     => '',
                'quantity_num'      => '',
                'quantity_title'    => '',
                'unit_price'        => '',
                'original_price'    => '',
                'insurance_price'   => '',
                'patient_price'     => '',
                'issue_date'        => '',
                'issue_person'      => '',
                'issue_person_name' => '',
                'doctor'            => '',
                'doctor_id'         => ''
        );
        if (empty($res['materialList'])) {
            for ($i=0; $i < 1; $i++){
                $res['materialList'][$i]    =   $material;
            }
        }
        else {
            array_push($res['materialList'], $material);
        }
        $this->assign('medicineList', $res['medicineList']);
        $this->assign('medIndex', 1);
        $this->assign('materialList', $res['materialList']);
        $this->assign('matIndex', 1);

        return $this->view->render('detail_input_medicine.html');
    }

    private function getTicketMedicineData($ticketId, $dateFrom,
            $dateTo, $filter){
        $medicineList  =   ORDataObject::factory('TicketMedicine')->getTicketMedicine($ticketId, $dateFrom, $dateTo, $filter);
        $materialList  =   ORDataObject::factory('TicketMaterial')->getTicketMaterials($ticketId, $dateFrom, $dateTo, $filter);
        $res['medicineList']    =   $medicineList;
        $res['materialList']    =   $materialList;

        return $res;
    }

    public function actionLoadTicketMedicinePage($ticketId=''){
    	if(isset($_GET['ticketId'])){
    		$ticketId =   $_GET['ticketId'];
    	}
    	$this->assign('ticketId', $ticketId);
    	return $this->view->render('ticket_medicine.html');
    }

    public function actionGetMedicineInfo($ticketId='', $medicineName=''){
        // Insurance type of the ticket
    	$insType  =   Celini::newORDO('Ticket', $ticketId)->get('insurance');
        $ctlMedicine    =   new C_Medicine();
        return  $ctlMedicine->getMedicineInfo($medicineName, $insType);
    }

    public function actionGetMaterialInfo($ticketId='', $materialName=''){
        // Insurance type of the ticket
        $insType  =   Celini::newORDO('Ticket', $ticketId)->get('insurance');
        $ctlMaterial    =   new C_MedicalMaterial();
        return  $ctlMaterial->getMaterialInfo($materialName, $insType);
    }

    /**
     * Save informatino on medicine and medical materials used to in a ticket
     *
     * @return json Status of saving, and a result message
     */
    public function actionSaveTicketMedicine(){
        $ticketId   =   $_GET['ticketId'];
        $issueDate  =   L10nHelper::getISODate($_GET['issueDate']);
        // Medicine
        $medNum     =   $_GET['medNum'];
        ORDataObject::factory('TicketMedicine')->deleteItem($ticketId, $issueDate);
        for ($i = 1; $i <= $medNum; $i++) {
            if(isset($_GET["medId_$i"]) && $_GET["medId_$i"] > 0) {
                $medicineId     =   $_GET["medId_$i"];
                $quantityNum    =   L10nHelper::getNumber($_GET["quanNum_$i"]);
                $quantityTitle  =   $_GET["quanTitle_$i"];
                $unitPrice      =   L10nHelper::getNumber($_GET["unitPrice_$i"]);
                $orgPrice       =   L10nHelper::getNumber($_GET["orgPrice_$i"]);
                $insPrice       =   L10nHelper::getNumber($_GET["insPrice_$i"]);
                $patPrice       =   L10nHelper::getNumber($_GET["patPrice_$i"]);
                $issuePerson    =   $_GET["issuePerson_$i"];
                $doctorId       =   $_GET["doctor_$i"];
                $objTicMed      =   ORDataObject::factory('TicketMedicine');
                $objTicMed->setData($ticketId, $medicineId, $quantityNum,
                    $quantityTitle, $unitPrice, $orgPrice, $insPrice, $patPrice,
                    $issueDate, $issuePerson, $doctorId);
                $objTicMed->persist();
            }
        }

        // Materials
        $matNum     =   $_GET['matNum'];
        ORDataObject::factory('TicketMaterial')->deleteItem($ticketId, $issueDate);
        for ($i = 1; $i <= $matNum ; $i++) {
            if(isset($_GET["matId_$i"]) && $_GET["matId_$i"] > 0) {
                $medicineId     =   $_GET["matId_$i"];
                $quantityNum    =   L10nHelper::getNumber($_GET["matQuanNum_$i"]);
                $quantityTitle  =   $_GET["matQuanTitle_$i"];
                $unitPrice      =   L10nHelper::getNumber($_GET["matUnitPrice_$i"]);
                $orgPrice       =   L10nHelper::getNumber($_GET["matOrgPrice_$i"]);
                $insPrice       =   L10nHelper::getNumber($_GET["matInsPrice_$i"]);
                $patPrice       =   L10nHelper::getNumber($_GET["matPatPrice_$i"]);
                $issuePerson    =   $_GET["matIssuePerson_$i"];
                $doctorId       =   $_GET["matDoctor_$i"];
                $objTicMed      =   ORDataObject::factory('TicketMaterial');
                $objTicMed->setData($ticketId, $medicineId, $quantityNum,
                    $quantityTitle, $unitPrice, $orgPrice, $insPrice, $patPrice,
                    $issueDate, $issuePerson, $doctorId);
                $objTicMed->persist();
            }
        }
        $response['code'] =   1;
        $response['message']   =   "";

        return json_encode($response);
    }

    /**
     * View medicines used to cure a patient
     *
     * @param int $patientId Patient Id
     * @return html Table of used medicine
     */
    public function actionViewPatientMedicine($patientId='') {
        if (isset($_GET['patientId'])) {
        	$patientId =   $_GET['patientId'];
        }
        $medicineList  =   ORDataObject::factory('TicketMedicine')->getMedicineByPatient($patientId);
        $this->assign('medicineList', $medicineList);
        $this->assign('medIndex', 1);

        return $this->view->render('element_medicine_list.html');
    }

    /**
     * View medical materials used to cure a patient
     *
     * @param int $patientId Patient Id
     * @return html Table of used materials
     */
    public function actionViewPatientMaterial($patientId='') {
        if (isset($_GET['patientId'])) {
            $patientId =   $_GET['patientId'];
        }
        $materialList  =   ORDataObject::factory('TicketMaterial')->getMaterialByPatient($patientId);
        $this->assign('materialList', $materialList);
        $this->assign('matIndex', 1);

        return $this->view->render('element_material_list.html');
    }
}
?>